package edu.neusoft.lyc.topic_one;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * User：lyc
 * Date：2017-11-25
 * Time：9:55
 * Description：传统IO示例代码
 */
public class TraditionalIO {
    public static void main(String[] args) {
        ServerSocket server = null;
        try {
            ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
            Integer port = 10010;
            //创建监听10010端口的服务端
            server = new ServerSocket(port);
            System.out.println(String.format("服务端初始化成功>>>>绑定%s端口", port));
            while (true) {
                //阻塞点1：获取客户端连接
                final Socket socket = server.accept();
                InetAddress inetAddress = socket.getInetAddress();
                System.out.println(String.format("检测到新客户端连接>>>>IP:%s", inetAddress));
                //主线程接收客户端连接，分配其他线程异步处理不同客户端的业务
                cachedThreadPool.execute(() -> handleBiz(socket));
                //主线程接收客户端连接后，同步阻塞处理一个客户端的业务
                // handleBiz(socket);
            }
        } catch (IOException e) {
            System.out.println("服务端获取客户端连接异常");
            e.printStackTrace();
        } finally {
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理具体业务
     *
     * @param socket
     */
    private static void handleBiz(Socket socket) {
        try {
            InputStream is = socket.getInputStream();
            byte[] buffer = new byte[1024];
            while (true) {
                //阻塞点2：读取客户端发送的数据
                int len = is.read(buffer);
                if (len > 0) {
                    System.out.println(new String(buffer, 0, len, "utf-8"));
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
                System.out.println("关闭客户端连接");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
